package com.example.demo.core.util;/**
 * Created by kete on 2017-10-30.
 */

import com.alibaba.fastjson.JSONObject;
import com.example.demo.core.support.StrKit;
import com.xiaoleilu.hutool.crypto.digest.DigestUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 作者：kete
 * 创建时间：2017-10-30 15:50
 * 功能描述：
 * 版本：
 */
public class WebUtil {

    private static Logger logger = LoggerFactory.getLogger(WebUtil.class);

    public static String accessSecret = "imQIWVZiX8qTo8hzFyCiQfKEOKygNZ5bQMC7BmusGbJ";
    public static String nodeName = null;
    public static String webdocsURL = null;
    public static boolean isWebdocs = false;
    public static String configPrefix = null;


    private static Object lockContext = new Object();



    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();

        return response;
    }

    public static HttpSession getSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getSession();
    }

    public static String[] domains = new String[]{"onelinkplus.com", "ebidding.qycg.com"};

    public static String getDomain() {
        HttpServletRequest request = WebUtil.getRequest();
        String host = request.getHeader("Host");
        if (StrKit.isEmpty(host)) return null;

        for (String domain : domains) {
            if (host.indexOf(domain) != -1) {
                return domain;
            }
        }

        return null;
    }

    public static void cookieSetDomain(Cookie cookie) {

        String domain = getDomain();
        if (StrKit.isNotEmpty(domain)) {
            cookie.setDomain("." + domain);
        }
    }

    public static boolean checkFileUrlSignature(String signature, String accessToken, String fileId) {

        logger.debug("signature=" + signature + " accessToken=" + accessToken + " fileId=" + fileId);
        String tmpStr = accessSecret + accessToken.toString() + fileId.toString();
        String tmpSignature =  DigestUtil.sha1Hex(tmpStr);
        if (StrKit.equals(tmpSignature, signature))
            return true;
        return false;
    }

    /**
     * 作者：闫广坤
     * 创建时间：2014-12-30 上午9:02:17
     * 方法描述：替换字符串。
     *
     * @param tplString 模板字符串。
     * @param dataModel 替换的数据。
     * @return
     */
    public static String replaceString(String tplString, Object dataModel) {

        if (dataModel == null) return tplString;

        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
            StringTemplateLoader stringLoader = new StringTemplateLoader();
            stringLoader.putTemplate("template", tplString);

            cfg.setTemplateLoader(stringLoader);
            Template template = cfg.getTemplate("template", "utf-8");
            template.setNumberFormat("0.#");

            String result = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataModel);

            return result;
        } catch (Exception e) {
            logger.error("模板:{},参数:{}", tplString, JSONObject.toJSONString(dataModel));
            e.printStackTrace();
            return "";
        }

    }

    public static String getAccessTokenSignature(String uuid) {

        HttpServletRequest request = WebUtil.getRequest();

        String userAgent = request.getHeader("User-Agent");
        String ipAddr = "";//WebUtil.getIpAddr();
        String tmpStr = uuid + userAgent + ipAddr + accessSecret;
        String accessToken = DigestUtil.sha1Hex(tmpStr);

        return accessToken;
    }


    public static boolean checkAccessTokenSignature(String signature, String uuid) {

        HttpServletRequest request = WebUtil.getRequest();
        String userAgent = request.getHeader("User-Agent");
        String ipAddr = "";//WebUtil.getIpAddr();
        String tmpStr = uuid + userAgent + ipAddr + accessSecret;
        //logger.info(">>>>>tmpStr = " + tmpStr);
        String tmpSignature =  DigestUtil.sha1Hex(tmpStr);
        //logger.info(">>>>>tmpSignature = " + tmpSignature);
        if (StrKit.equals(tmpSignature, signature))
            return true;
        return false;
    }


    public static String getIpAddr() {
        return getIpAddress(WebUtil.getRequest());
    }

    private static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 作者：闫广坤
     * 创建时间：2016年5月19日 上午11:10:51
     * 方法描述：获取文件url签名，sha1加密。
     *
     * @param accessToken 访问令牌。
     * @param fileId      文件id。
     * @return 文件url签名字符串。
     */
    public static String getFileUrlSignature(String accessToken, String fileId) {

        String tmpStr = accessSecret + accessToken.toString() + fileId.toString();
        String signature = DigestUtil.sha1Hex(tmpStr);

        logger.debug("signature=" + signature + " accessToken=" + accessToken + " fileId=" + fileId);
        return signature;
    }
}
